package com.sh.apiorder.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.sh.apicommon.entity.Order;
import com.sh.apicommon.service.ApiBackendService;
import com.sh.apiorder.service.TOrderService;
import jakarta.annotation.Resource;
import jakarta.jms.JMSException;
import jakarta.jms.Session;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class OrderPaySuccessListener {

    @Resource
    private TOrderService tOrderService;
    @Resource
    private ApiBackendService apiBackendService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public static final Integer ORDER_PAY_SUCCESS_STATUS = 1;   // 修改订单状态 1 支付成功
    public static final String FROM_QUEUE_ORDER_PAY = "from_queue_order_pay:";

    @Transactional(rollbackFor = Exception.class)
    @JmsListener(destination = "orderPayInfo")
    public void invokeCountConsumer(String outTradeNo, Session session) throws JMSException {
        System.out.println("接收到消息：" + outTradeNo);
        // 消费端的幂等性
        // GET order:pay:123456
        String orderOk = stringRedisTemplate.opsForValue().get(FROM_QUEUE_ORDER_PAY + outTradeNo);
        if ( orderOk!=null){   // 如果订单提交过了
            return;
        }
        // 改订单表 和 user_interface 表 的状态
        if (outTradeNo == null) {
            throw new RuntimeException("消息为空");
        }

        // 改订单状态
        UpdateWrapper<Order> orderUpdateWrapper = new UpdateWrapper<>();
        orderUpdateWrapper.eq("orderSn", outTradeNo);
        orderUpdateWrapper.set("status", ORDER_PAY_SUCCESS_STATUS);
        boolean update = tOrderService.update(orderUpdateWrapper);   // 改订单状态


        // 改user_interface_info表的状态  分配次数
        // 根据 订单号  拿到订单信息  取 用户id  购买数量  接口id
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("orderSn", outTradeNo);
        Order one = tOrderService.getOne(orderQueryWrapper);
        if (one == null) {
            throw new RuntimeException("订单不存在");
        }
        Long userId = one.getUserId();
        Long interfaceId = one.getInterfaceId();
        Integer count = one.getCount();
        // 改user_interface_info表的状态  分配次数
        boolean updateInvokeCount = apiBackendService.updateUserInterfaceInvokeCount(userId, interfaceId, count);
        if (!update || !updateInvokeCount) {
            log.error("订单支付成功，更新失败");
            session.rollback();
        }
        // 消费端的幂等性
        stringRedisTemplate.opsForValue().set(FROM_QUEUE_ORDER_PAY+outTradeNo,"OK",30, TimeUnit.SECONDS);
    }

}
